package com.eshop.common.strategy.uploadImg;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class NginxUpload implements upLoadImg{
    @Override
    public void getImg(String path,String fileName,HttpServletResponse response) {
        ServletOutputStream outputStream = null;
        InputStream decryptInputStream = getInputStream(path,fileName);
        try{
            response.reset();
            outputStream = response.getOutputStream();
            response.setHeader("Pragma","no-cache");
            response.setHeader("Cache-Control","no-cache");
            response.setDateHeader("Expires",0);
            //因为我的图片是png格式的，所以我在contentType写死了。实际开发中，根据图片类型来修改相应的contentType
            response.setContentType("image/png");
            // 在http响应中输出流
            byte[] cache = new byte[1024];
            int nRead = 0;
            while ((nRead = decryptInputStream.read(cache)) != -1) {
                outputStream.write(cache, 0, nRead);
                outputStream.flush();
            }
            outputStream.flush();
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    //获取输入流
    public static InputStream getInputStream(String file, String fileName) {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL("http://110.40.176.175:91/static/api/file/"+file+"/"+fileName);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(3000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("GET");
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == 200) {
                inputStream = httpURLConnection.getInputStream();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return inputStream;
    }


}
